/* The code examples copyrighted by Nokia Corporation that are included to
 * this material are licensed to you under following MIT-style License:
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#include <MApplication>
#include <QDeclarativeView>
#include <QDeclarativeContext>
#include <QMessageBox>
#include <QDebug>

#include <QFile>
#include <QFileInfo>

#include <qmfclient/qmailnamespace.h>
#include <qmfclient/QMailMessage>
#include <qmfclient/QMailAddress>
#include <qmfclient/QMailStore>
#include <qmfclient/QMailTransmitAction>
#include <qmfclient/QMailServiceAction>
#include <qmfclient/QMailTimeStamp>

#include "mymailaccountlistmodel.h"

#include "sendmailexample.h"

//NOTE: This example assumes there already are configured accounts.

SendMailExample::SendMailExample(QDeclarativeContext *context) :
    m_transmitAction(0)
{
    accountListModel=new MyMailAccountListModel();
    context->setContextProperty("SendMailExample", this);
    context->setContextProperty("SenderAccountModel", accountListModel);
}

SendMailExample::~SendMailExample()
{
    delete accountListModel;
}

// try to send mail
bool SendMailExample::sendMail(const QString & receiver, const QString &subject, const QString &mailText, int senderIndex)
{
    QString attachmentText("");
    if(senderIndex < 0) {
        return false;
    }
    // Check information for validity
    if(receiver.isEmpty()) {
        return false;
    }
    // Abort if selected sender is not valid
    QMailAccountId sender = accountListModel->idFromIndex(accountListModel->index(senderIndex));
    if(!sender.isValid()) {
        return false;
    }
    // Abort if attachment selected, but file doesn't exist
    if (!attachmentText.isEmpty()) {
        QFile f(attachmentText);
        if (!f.exists()) {
             return false;
        }
    }
    QMailMessage msg;
    //Set receiver to entered address
    msg.setTo(QMailAddress(receiver));
    msg.setSubject(subject);
    msg.setDate(QMailTimeStamp::currentDateTime());
    msg.setStatus(QMailMessage::Outgoing | 
                  QMailMessage::ContentAvailable | 
                  QMailMessage::PartialContentAvailable |
                  QMailMessage::Read |
                  QMailMessage::Outbox, true);
    QMailMessageContentType type("text/plain; charset=UTF-8");
    if (attachmentText.isEmpty()) {
        msg.setBody(QMailMessageBody::fromData(mailText, type, QMailMessageBody::Base64));
    }
    else {
        // Message
        QMailMessagePart textPart;
        textPart.setBody(QMailMessageBody::fromData(mailText, type, QMailMessageBody::Base64));
        msg.setMultipartType(QMailMessagePartContainer::MultipartMixed);
        msg.appendPart(textPart);
        // Attachment
        QFileInfo fi(attachmentText);
        QString partName(fi.fileName());
        QString filePath(fi.absoluteFilePath());

        QMailMessageContentType type(QMail::mimeTypeFromFileName(attachmentText).toLatin1());
        type.setName(partName.toLatin1());

        QMailMessageContentDisposition disposition(QMailMessageContentDisposition::Attachment);
        disposition.setFilename(partName.toLatin1());
        disposition.setSize(fi.size());

        QMailMessagePart attachmentPart = QMailMessagePart::fromFile(filePath, disposition, type, QMailMessageBody::Base64, QMailMessageBody::RequiresEncoding);
        msg.appendPart(attachmentPart);
    }
    msg.setMessageType(QMailMessage::Email);

    // Set sender to currently selected account
    msg.setParentAccountId(sender);
    msg.setFrom(QMailAccount(sender).fromAddress());

    msg.setParentFolderId(QMailFolder::LocalStorageFolderId);

    if(!m_transmitAction) {
        m_transmitAction = new QMailTransmitAction(this);
        connect(m_transmitAction, SIGNAL(activityChanged(const QMailServiceAction::Activity &)),
                this, SLOT(activityChanged(const QMailServiceAction::Activity &)));
    }
    // Add message to store & try to send it
    if(QMailStore::instance()->addMessage(&msg)) {
        m_transmitAction->transmitMessages(sender);
        return true;
    }
    return false;
}

void SendMailExample::activityChanged(const QMailServiceAction::Activity & a)
{
    QString text;
    switch(a)
    {
        case QMailServiceAction::Successful:
            break;
        case QMailServiceAction::Failed:
            break;
        default:
            break;
    }
}

int main(int argc, char *argv[])
{
    MApplication app(argc, argv);
    QDeclarativeView view;
    SendMailExample sendMailExample(view.rootContext());
    view.setSource(QUrl::fromLocalFile("/usr/share/sendmail-qml-example/sendmail-qml-example.qml"));
    view.showFullScreen();

    return app.exec();
}
